import axios from 'axios'
import { Toast } from 'vant'
import { HttpResponseType } from '../types/common'

const HTTP_SERVER = axios.create()
const CancelToken = axios.CancelToken
const controller = new AbortController()

HTTP_SERVER.defaults.baseURL = 'http://backend-api-01.newbee.ltd/api/v1/';
HTTP_SERVER.defaults.headers.post['Content-Type'] = 'application/json'
HTTP_SERVER.defaults.headers['token' as keyof typeof HTTP_SERVER.defaults.headers] = JSON.parse(localStorage.getItem('vuex') || JSON.stringify({token: ''})).token || ''



let pending: any = []
const removePending = (config: any) => {
  console.log('pending',pending);
  for(let p in pending){
    if(pending[p].u === config.url.split('?')[0] + '&' + config.method) { 
    //当当前请求在数组中存在时执行函数体
        pending[p].f(); //执行取消操作
        pending.splice(p, 1); //数组移除当前请求
    }
  }
}

// 添加请求拦截器
// request interceptor
HTTP_SERVER.interceptors.request.use(function (config: any) {
  removePending(config)
  config.cancelToken = new CancelToken((c)=>{
    // pending存放每一次请求的标识，一般是url + 参数名 + 请求方法，当然你可以自己定义
    pending.push({ u: config.url.split('?')[0] +'&' + config.method, f: c});//config.data为请求参数
  });
  return config;
}, function (error: any) {
  return Promise.reject(error);
});

// response interceptor
HTTP_SERVER.interceptors.response.use(function (response: any): HttpResponseType {
  return response.data;
}, function (error: any) {
  Toast.fail('服务异常')
  return Promise.reject(error);
});

export default HTTP_SERVER
